// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using MySql.Data.MySqlClient;

namespace SnapObjects.Data.MySql
{
    internal class MySqlAdoDbCommand : AdoDbCommand
    {
        public MySqlAdoDbCommand(
            [NotNull] string sqlText,
            IEnumerable<IAdoDbParameter> parameters,
            bool addExceptionToTransaction,
            CommandType commandType = CommandType.Text)
            : base(sqlText, parameters, addExceptionToTransaction, commandType)
        {

        }

        protected override string BuildNoExecCommandText(DataContext context, string commandText)
        {
            return $"explain {commandText}";
        }

        public override int ExecuteNonQuery(DataContext dataContext)
        {
            var ret = base.ExecuteNonQuery(dataContext);

            return ret == -1 ? 0 : ret;
        }

        public override async Task<int> ExecuteNonQueryAsync(
            DataContext dataContext, CancellationToken cancellationToken = default)
        {
            var ret = await base.ExecuteNonQueryAsync(dataContext, cancellationToken);

            return ret == -1 ? 0 : ret;
        }

        protected override int GetSqlDbCode(Exception innerException)
        {
            if (innerException is MySqlException ex)
            {
                return ex.Number;
            }

            return -1;
        }
    }
}
